class PageBuilder {
    constructor() {
        this.elements = [];
        this.selectedElement = null;
        this.elementIdCounter = 0;
        this.canvas = document.getElementById('canvas');
        this.propertiesContent = document.getElementById('propertiesContent');
        this.background = { color: '#ffffff', image: '' };
        
        // 使用px单位，以375px为设计基准
        
        this.init();
    }

    // Toast提示功能
    showToast(message, type = 'info', duration = 3000) {
        const container = document.getElementById('toastContainer');
        const toast = document.createElement('div');
        toast.className = `toast ${type}`;
        
        const icons = {
            success: '✅',
            error: '❌',
            warning: '⚠️',
            info: 'ℹ️'
        };
        
        toast.innerHTML = `
            <span class="toast-icon">${icons[type] || icons.info}</span>
            <span class="toast-content">${message}</span>
            <button class="toast-close" onclick="this.parentElement.remove()">×</button>
        `;
        
        container.appendChild(toast);
        
        // 触发显示动画
        setTimeout(() => {
            toast.classList.add('show');
        }, 10);
        
        // 自动隐藏
        if (duration > 0) {
            setTimeout(() => {
                this.hideToast(toast);
            }, duration);
        }
        
        return toast;
    }

    hideToast(toast) {
        toast.classList.add('hide');
        setTimeout(() => {
            if (toast.parentElement) {
                toast.remove();
            }
        }, 300);
    }

    // 便捷方法
    showSuccess(message, duration = 3000) {
        return this.showToast(message, 'success', duration);
    }

    showError(message, duration = 4000) {
        return this.showToast(message, 'error', duration);
    }

    showWarning(message, duration = 3000) {
        return this.showToast(message, 'warning', duration);
    }

    showInfo(message, duration = 3000) {
        return this.showToast(message, 'info', duration);
    }

    // 直接使用px单位，无需转换

    init() {
        this.setupEventListeners();
        this.setupDragAndDrop();
        this.setupMobileAdaptation();
        this.setupStructureLibrary();
        this.setupAccordion();
    }

    // 移动端适配设置
    setupMobileAdaptation() {
        // 检测是否为移动设备
        const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
        
        if (isMobile) {
            // 移动端优化
            this.canvas.style.minHeight = '100vh';
            this.canvas.style.border = '1px solid #ddd';
            
            // 添加触摸事件支持
            this.setupTouchEvents();
        }
    }

    // 设置触摸事件
    setupTouchEvents() {
        let startX, startY, startLeft, startTop, offsetX, offsetY;
        let isDragging = false;
        let currentElement = null;

        this.canvas.addEventListener('touchstart', (e) => {
            const touch = e.touches[0];
            const element = e.target.closest('.canvas-element');
            
            if (element) {
                e.preventDefault();
                isDragging = true;
                currentElement = element;
                
                // 获取触摸点相对于元素的位置
                const rect = element.getBoundingClientRect();
                offsetX = touch.clientX - rect.left;
                offsetY = touch.clientY - rect.top;
                
                startX = touch.clientX;
                startY = touch.clientY;
                startLeft = parseInt(element.style.left) || 0;
                startTop = parseInt(element.style.top) || 0;
                
                // 添加拖拽样式
                element.style.cursor = 'grabbing';
                element.style.zIndex = '1000';
                
                this.selectElement(this.elements.find(el => el.id === element.id));
            }
        });

        this.canvas.addEventListener('touchmove', (e) => {
            if (isDragging && currentElement) {
                e.preventDefault();
                const touch = e.touches[0];
                
                // 计算相对于画布的位置
                const canvasRect = this.canvas.getBoundingClientRect();
                let newX = touch.clientX - canvasRect.left - offsetX - 2; // 减去边框宽度
                let newY = touch.clientY - canvasRect.top - offsetY - 2;  // 减去边框宽度
                
                // 边界检查，确保元素不超出画布
                const elementWidth = parseInt(currentElement.style.width) || 100;
                const elementHeight = parseInt(currentElement.style.height) || 50;
                const canvasWidth = 375 - 4; // 画布宽度减去边框
                const canvasHeight = 667 - 4; // 画布高度减去边框
                
                newX = Math.max(0, Math.min(newX, canvasWidth - elementWidth));
                newY = Math.max(0, Math.min(newY, canvasHeight - elementHeight));
                
                currentElement.style.left = newX + 'px';
                currentElement.style.top = newY + 'px';
                
                // 更新元素数据
                const elementData = this.elements.find(el => el.id === currentElement.id);
                if (elementData) {
                    elementData.x = newX;
                    elementData.y = newY;
                }
            }
        });

        this.canvas.addEventListener('touchend', (e) => {
            if (isDragging && currentElement) {
                isDragging = false;
                currentElement.style.cursor = 'move';
                currentElement.style.zIndex = '';
                currentElement = null;
            }
        });
    }

    setupEventListeners() {
        // 工具栏按钮
        document.getElementById('saveBtn').addEventListener('click', () => this.showSaveModal());
        document.getElementById('loadBtn').addEventListener('click', () => this.showLoadModal());
        document.getElementById('previewBtn').addEventListener('click', () => this.generatePreview());
        document.getElementById('backgroundBtn').addEventListener('click', () => this.showBackgroundModal());
        document.getElementById('clearCanvas').addEventListener('click', () => this.clearCanvas());

        // 模态框关闭
        document.querySelectorAll('.close').forEach(closeBtn => {
            closeBtn.addEventListener('click', (e) => {
                e.target.closest('.modal').style.display = 'none';
            });
        });

        // 背景设置
        document.getElementById('applyBackground').addEventListener('click', () => this.applyBackground());

        // 保存功能
        document.getElementById('confirmSave').addEventListener('click', () => this.savePage());

        // 读取功能
        document.getElementById('confirmLoad').addEventListener('click', () => this.loadPage());

        // 点击画布取消选择
        this.canvas.addEventListener('click', (e) => {
            // 只有当点击的是画布本身（不是子元素）时才取消选择
            if (e.target === this.canvas || e.target.classList.contains('canvas-placeholder')) {
                this.selectElement(null);
            }
        });

        // 防止画布被意外清空
        this.canvas.addEventListener('DOMNodeRemoved', (e) => {
            console.warn('Canvas content removed:', e.target);
        });
    }

    setupDragAndDrop() {
        // 元素拖拽
        document.querySelectorAll('.element-item').forEach(item => {
            item.addEventListener('dragstart', (e) => {
                e.dataTransfer.setData('text/plain', e.target.dataset.type);
            });
        });

        // 画布拖拽处理
        this.canvas.addEventListener('dragover', (e) => {
            e.preventDefault();
            this.canvas.classList.add('drag-over');
        });

        this.canvas.addEventListener('dragleave', () => {
            this.canvas.classList.remove('drag-over');
        });

        this.canvas.addEventListener('drop', (e) => {
            e.preventDefault();
            this.canvas.classList.remove('drag-over');
            
            const elementType = e.dataTransfer.getData('text/plain');
            const rect = this.canvas.getBoundingClientRect();
            // 计算相对于画布内容区域的位置（考虑边框）
            const x = e.clientX - rect.left - 2; // 减去边框宽度
            const y = e.clientY - rect.top - 2;  // 减去边框宽度
            
            this.addElement(elementType, x, y);
        });
    }

    addElement(type, x, y) {
        const elementId = `element_${++this.elementIdCounter}`;
        const element = {
            id: elementId,
            type: type,
            content: this.getDefaultContent(type),
            style: this.getDefaultStyle(type),
            x: x,
            y: y
        };

        this.elements.push(element);
        this.renderElement(element);
        this.selectElement(element);
        
        // 调试信息
        console.log('Element added:', element.id, 'Total elements:', this.elements.length);
    }

    getDefaultContent(type) {
        const defaults = {
            text: '双击编辑文本',
            image: '/images/demo.webp',
            button: '按钮',
            input: '请输入内容'
        };
        return defaults[type] || '';
    }

    getDefaultStyle(type) {
        const defaults = {
            text: {
                width: '120px',
                height: '40px',
                fontSize: '14px',
                color: '#333333',
                backgroundColor: 'transparent',
                textAlign: 'center',
                lineHeight: '40px'
            },
            image: {
                width: '150px',
                height: '100px',
                objectFit: 'cover'
            },
            button: {
                width: '100px',
                height: '40px',
                fontSize: '14px',
                color: '#ffffff',
                backgroundColor: '#007bff',
                border: 'none',
                borderRadius: '6px',
                cursor: 'pointer'
            },
            input: {
                width: '150px',
                height: '40px',
                fontSize: '14px',
                padding: '0 10px',
                border: '1px solid #ddd',
                borderRadius: '6px'
            }
        };
        return defaults[type] || {};
    }

    renderElement(element) {
        // 检查元素是否已存在，如果存在则先移除
        const existingElement = document.getElementById(element.id);
        if (existingElement) {
            existingElement.remove();
        }
        
        const elementDiv = document.createElement('div');
        elementDiv.className = 'canvas-element';
        elementDiv.id = element.id;
        elementDiv.style.left = element.x + 'px';
        elementDiv.style.top = element.y + 'px';
        
        // 应用样式
        Object.entries(element.style).forEach(([key, value]) => {
            // 将驼峰命名转换为CSS属性名
            const cssKey = key.replace(/([A-Z])/g, '-$1').toLowerCase();
            elementDiv.style[cssKey] = value;
        });

        // 根据类型创建内容
        switch (element.type) {
            case 'text':
                elementDiv.textContent = element.content;
                elementDiv.addEventListener('dblclick', () => this.editText(element));
                break;
            case 'image':
                const img = document.createElement('img');
                img.src = element.content;
                img.style.width = '100%';
                img.style.height = '100%';
                img.style.objectFit = 'cover';
                img.style.display = 'block';
                
                // 添加图片加载错误处理
                img.onerror = function() {
                    console.error('图片加载失败:', element.content);
                    this.style.backgroundColor = '#f0f0f0';
                    this.style.border = '2px dashed #ccc';
                    this.style.display = 'flex';
                    this.style.alignItems = 'center';
                    this.style.justifyContent = 'center';
                    this.style.color = '#999';
                    this.style.fontSize = '12px';
                    this.textContent = '图片加载失败';
                };
                
                img.onload = function() {
                    console.log('图片加载成功:', element.content);
                };
                
                elementDiv.appendChild(img);
                break;
            case 'button':
                elementDiv.textContent = element.content;
                break;
            case 'input':
                const input = document.createElement('input');
                input.type = 'text';
                input.placeholder = element.content;
                input.style.width = '100%';
                input.style.height = '100%';
                input.style.border = 'none';
                input.style.background = 'transparent';
                elementDiv.appendChild(input);
                break;
            case 'grid':
                // 创建网格容器
                elementDiv.className = 'canvas-element grid-container';
                elementDiv.innerHTML = `
                    <div class="grid-header">
                        <span class="grid-title">${element.cols || 2}列网格</span>
                        <span class="grid-hint">拖拽元素到此处</span>
                    </div>
                    <div class="grid-content" id="grid-content-${element.id}"></div>
                `;
                // 设置网格为拖拽目标
                elementDiv.setAttribute('data-grid-id', element.id);
                elementDiv.classList.add('grid-drop-zone');
                break;
        }

        // 添加调整大小手柄
        this.addResizeHandles(elementDiv);

        // 添加事件监听器
        elementDiv.addEventListener('click', (e) => {
            e.stopPropagation();
            this.selectElement(element);
        });

        // 添加拖拽功能
        this.makeDraggable(elementDiv, element);

        this.canvas.appendChild(elementDiv);
    }

    addResizeHandles(elementDiv) {
        const handles = ['nw', 'ne', 'sw', 'se'];
        handles.forEach(handle => {
            const handleDiv = document.createElement('div');
            handleDiv.className = `resize-handle ${handle}`;
            elementDiv.appendChild(handleDiv);
        });
    }

    makeDraggable(elementDiv, element) {
        let isDragging = false;
        let startX, startY, startLeft, startTop, offsetX, offsetY;

        elementDiv.addEventListener('mousedown', (e) => {
            if (e.target.classList.contains('resize-handle')) {
                this.handleResize(e, elementDiv, element);
                return;
            }

            e.preventDefault();
            isDragging = true;
            
            // 获取鼠标相对于元素的位置
            const rect = elementDiv.getBoundingClientRect();
            offsetX = e.clientX - rect.left;
            offsetY = e.clientY - rect.top;
            
            startX = e.clientX;
            startY = e.clientY;
            startLeft = parseInt(elementDiv.style.left) || 0;
            startTop = parseInt(elementDiv.style.top) || 0;

            // 添加拖拽样式
            elementDiv.style.cursor = 'grabbing';
            elementDiv.style.zIndex = '1000';

            document.addEventListener('mousemove', handleMouseMove);
            document.addEventListener('mouseup', handleMouseUp);
        });

        const handleMouseMove = (e) => {
            if (!isDragging) return;
            
            e.preventDefault();
            
            // 计算相对于画布的位置
            const canvasRect = this.canvas.getBoundingClientRect();
            let newX = e.clientX - canvasRect.left - offsetX - 2; // 减去边框宽度
            let newY = e.clientY - canvasRect.top - offsetY - 2;  // 减去边框宽度
            
            // 边界检查，确保元素不超出画布
            const elementWidth = parseInt(elementDiv.style.width) || 100;
            const elementHeight = parseInt(elementDiv.style.height) || 50;
            const canvasWidth = 375 - 4; // 画布宽度减去边框
            const canvasHeight = 667 - 4; // 画布高度减去边框
            
            newX = Math.max(0, Math.min(newX, canvasWidth - elementWidth));
            newY = Math.max(0, Math.min(newY, canvasHeight - elementHeight));
            
            element.x = newX;
            element.y = newY;
            
            elementDiv.style.left = element.x + 'px';
            elementDiv.style.top = element.y + 'px';
        };

        const handleMouseUp = () => {
            if (!isDragging) return;
            
            isDragging = false;
            elementDiv.style.cursor = 'move';
            elementDiv.style.zIndex = '';
            
            document.removeEventListener('mousemove', handleMouseMove);
            document.removeEventListener('mouseup', handleMouseUp);
        };
    }

    handleResize(e, elementDiv, element) {
        e.stopPropagation();
        const handle = e.target.className.split(' ')[1];
        let isResizing = true;
        let startX = e.clientX;
        let startY = e.clientY;
        let startWidth = parseInt(elementDiv.style.width) || 100;
        let startHeight = parseInt(elementDiv.style.height) || 50;
        let startLeft = element.x || 0;
        let startTop = element.y || 0;

        document.addEventListener('mousemove', handleResizeMove);
        document.addEventListener('mouseup', handleResizeUp);

        function handleResizeMove(e) {
            if (!isResizing) return;
            
            const deltaX = e.clientX - startX;
            const deltaY = e.clientY - startY;
            
            let newWidth = startWidth;
            let newHeight = startHeight;
            let newLeft = startLeft;
            let newTop = startTop;

            if (handle.includes('e')) newWidth = startWidth + deltaX;
            if (handle.includes('w')) {
                newWidth = startWidth - deltaX;
                newLeft = startLeft + deltaX;
            }
            if (handle.includes('s')) newHeight = startHeight + deltaY;
            if (handle.includes('n')) {
                newHeight = startHeight - deltaY;
                newTop = startTop + deltaY;
            }

            const finalWidth = Math.max(50, newWidth);
            const finalHeight = Math.max(30, newHeight);
            
            // 边界检查，确保不超出画布
            const canvasWidth = 375 - 4;
            const canvasHeight = 667 - 4;
            const maxWidth = canvasWidth - newLeft;
            const maxHeight = canvasHeight - newTop;
            
            const constrainedWidth = Math.min(finalWidth, maxWidth);
            const constrainedHeight = Math.min(finalHeight, maxHeight);
            
            elementDiv.style.width = constrainedWidth + 'px';
            elementDiv.style.height = constrainedHeight + 'px';
            elementDiv.style.left = newLeft + 'px';
            elementDiv.style.top = newTop + 'px';

            element.style.width = elementDiv.style.width;
            element.style.height = elementDiv.style.height;
            element.x = newLeft;
            element.y = newTop;
        }

        function handleResizeUp() {
            isResizing = false;
            document.removeEventListener('mousemove', handleResizeMove);
            document.removeEventListener('mouseup', handleResizeUp);
        }
    }

    selectElement(element) {
        // 移除之前的选择
        document.querySelectorAll('.canvas-element.selected').forEach(el => {
            el.classList.remove('selected');
        });

        this.selectedElement = element;

        if (element) {
            const elementDiv = document.getElementById(element.id);
            if (elementDiv) {
                elementDiv.classList.add('selected');
                this.showElementProperties(element);
            } else {
                console.warn('Element not found in DOM:', element.id);
            }
        } else {
            this.showElementProperties(null);
        }
    }

    showElementProperties(element) {
        if (!element) {
            this.propertiesContent.innerHTML = '<p class="placeholder">选择一个元素来编辑属性</p>';
            return;
        }

        const propertiesHTML = this.generatePropertiesHTML(element);
        this.propertiesContent.innerHTML = propertiesHTML;
        this.setupPropertyListeners(element);
    }

    generatePropertiesHTML(element) {
        let html = `
            <div class="form-group">
                <label>内容:</label>
                <input type="text" id="elementContent" value="${element.content}">
            </div>
        `;

        // 根据元素类型显示不同的属性
        if (element.type === 'text') {
            html += `
                <div class="form-group">
                    <label>字体大小 (px):</label>
                    <input type="number" id="fontSize" value="${parseInt(element.style.fontSize)}" step="1">
                </div>
                <div class="form-group">
                    <label>字体颜色:</label>
                    <input type="color" id="textColor" value="${element.style.color}">
                </div>
                <div class="form-group">
                    <label>文本对齐:</label>
                    <select id="textAlign">
                        <option value="left" ${element.style.textAlign === 'left' ? 'selected' : ''}>居左</option>
                        <option value="center" ${element.style.textAlign === 'center' ? 'selected' : ''}>居中</option>
                        <option value="right" ${element.style.textAlign === 'right' ? 'selected' : ''}>居右</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>背景颜色:</label>
                    <input type="color" id="backgroundColor" value="${element.style.backgroundColor || '#ffffff'}">
                </div>
            `;
        } else if (element.type === 'image') {
            html += `
                <div class="form-group">
                    <label>图片URL:</label>
                    <input type="url" id="imageUrl" value="${element.content}">
                </div>
            `;
        } else if (element.type === 'button') {
            html += `
                <div class="form-group">
                    <label>按钮文字:</label>
                    <input type="text" id="buttonText" value="${element.content}">
                </div>
                <div class="form-group">
                    <label>背景颜色:</label>
                    <input type="color" id="buttonBgColor" value="${element.style.backgroundColor}">
                </div>
                <div class="form-group">
                    <label>文字颜色:</label>
                    <input type="color" id="buttonTextColor" value="${element.style.color}">
                </div>
            `;
        }

        html += `
            <div class="form-group">
                <label>宽度 (px):</label>
                <input type="number" id="elementWidth" value="${parseInt(element.style.width)}" step="1">
            </div>
            <div class="form-group">
                <label>高度 (px):</label>
                <input type="number" id="elementHeight" value="${parseInt(element.style.height)}" step="1">
            </div>
            <div class="form-group">
                <button id="deleteElement" class="btn btn-danger">删除元素</button>
            </div>
        `;

        return html;
    }

    setupPropertyListeners(element) {
        // 内容更新
        const contentInput = document.getElementById('elementContent');
        if (contentInput) {
            contentInput.addEventListener('input', (e) => {
                element.content = e.target.value;
                this.updateElementDisplay(element);
            });
        }

        // 样式更新
        const styleInputs = ['fontSize', 'textColor', 'textAlign', 'backgroundColor', 'imageUrl', 'buttonText', 'buttonBgColor', 'buttonTextColor', 'elementWidth', 'elementHeight'];
        styleInputs.forEach(inputId => {
            const input = document.getElementById(inputId);
            if (input) {
                input.addEventListener('input', (e) => {
                    this.updateElementStyle(element, inputId, e.target.value);
                });
                // 为select元素添加change事件
                if (input.tagName === 'SELECT') {
                    input.addEventListener('change', (e) => {
                        this.updateElementStyle(element, inputId, e.target.value);
                    });
                }
            }
        });

        // 删除元素
        const deleteBtn = document.getElementById('deleteElement');
        if (deleteBtn) {
            deleteBtn.addEventListener('click', () => {
                this.deleteElement(element);
            });
        }
    }

    updateElementStyle(element, inputId, value) {
        const elementDiv = document.getElementById(element.id);
        
        switch (inputId) {
            case 'fontSize':
                element.style.fontSize = value + 'px';
                elementDiv.style.fontSize = value + 'px';
                break;
            case 'textColor':
                element.style.color = value;
                elementDiv.style.color = value;
                break;
            case 'textAlign':
                element.style.textAlign = value;
                elementDiv.style.textAlign = value;
                // 强制重新渲染元素以确保样式生效
                this.renderElement(element);
                // 重新生成属性面板以更新选择框的选中状态
                this.showElementProperties(element);
                break;
            case 'backgroundColor':
                element.style.backgroundColor = value;
                elementDiv.style.backgroundColor = value;
                break;
            case 'imageUrl':
                element.content = value;
                const img = elementDiv.querySelector('img');
                if (img) img.src = value;
                break;
            case 'buttonText':
                element.content = value;
                elementDiv.textContent = value;
                break;
            case 'buttonBgColor':
                element.style.backgroundColor = value;
                elementDiv.style.backgroundColor = value;
                break;
            case 'buttonTextColor':
                element.style.color = value;
                elementDiv.style.color = value;
                break;
            case 'elementWidth':
                element.style.width = value + 'px';
                elementDiv.style.width = value + 'px';
                break;
            case 'elementHeight':
                element.style.height = value + 'px';
                elementDiv.style.height = value + 'px';
                break;
        }
    }

    updateElementDisplay(element) {
        const elementDiv = document.getElementById(element.id);
        if (element.type === 'text' || element.type === 'button') {
            elementDiv.textContent = element.content;
        }
    }

    editText(element) {
        const newText = prompt('编辑文本:', element.content);
        if (newText !== null) {
            element.content = newText;
            this.updateElementDisplay(element);
        }
    }

    deleteElement(element) {
        const elementDiv = document.getElementById(element.id);
        if (elementDiv) {
            elementDiv.remove();
        }
        this.elements = this.elements.filter(el => el.id !== element.id);
        this.selectElement(null);
    }

    clearCanvas() {
        // 创建确认对话框
        const confirmToast = this.showToast('确定要清空画布吗？', 'warning', 0);
        confirmToast.innerHTML = `
            <span class="toast-icon">⚠️</span>
            <span class="toast-content">确定要清空画布吗？</span>
            <div style="display: flex; gap: 8px; margin-left: 10px;">
                <button onclick="this.closest('.toast').remove(); window.pageBuilder._confirmClearCanvas()" 
                        style="background: #4CAF50; color: white; border: none; padding: 4px 12px; border-radius: 4px; cursor: pointer; font-size: 12px;">
                    确定
                </button>
                <button onclick="this.closest('.toast').remove()" 
                        style="background: #f44336; color: white; border: none; padding: 4px 12px; border-radius: 4px; cursor: pointer; font-size: 12px;">
                    取消
                </button>
            </div>
        `;
    }

    _confirmClearCanvas() {
        this.elements = [];
        this.canvas.innerHTML = '<div class="canvas-placeholder"><p>拖拽左侧元素到此处开始设计</p></div>';
        this.selectElement(null);
        this.showSuccess('画布已清空');
    }

    showBackgroundModal() {
        document.getElementById('bgColor').value = this.background.color;
        document.getElementById('bgImage').value = this.background.image || '';
        document.getElementById('backgroundModal').style.display = 'block';
    }

    applyBackground() {
        this.background.color = document.getElementById('bgColor').value;
        this.background.image = document.getElementById('bgImage').value;
        
        // 只应用到画布区域
        this.canvas.style.backgroundColor = this.background.color;
        if (this.background.image) {
            this.canvas.style.backgroundImage = `url(${this.background.image})`;
            this.canvas.style.backgroundSize = 'cover';
            this.canvas.style.backgroundPosition = 'center';
            this.canvas.style.backgroundRepeat = 'no-repeat';
        } else {
            this.canvas.style.backgroundImage = 'none';
            this.canvas.style.backgroundSize = 'initial';
            this.canvas.style.backgroundPosition = 'initial';
            this.canvas.style.backgroundRepeat = 'initial';
        }
        
        document.getElementById('backgroundModal').style.display = 'none';
        this.showSuccess('背景设置已应用到画布');
    }

    showSaveModal() {
        document.getElementById('saveFilename').value = '';
        document.getElementById('saveModal').style.display = 'block';
    }

    async savePage() {
        const filename = document.getElementById('saveFilename').value.trim();
        if (!filename) {
            this.showError('请输入文件名');
            return;
        }

        const pageData = {
            background: this.background,
            elements: this.elements
        };

        try {
            const response = await fetch('/api/save', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ pageData, filename })
            });

            const result = await response.json();
            if (result.success) {
                this.showSuccess('保存成功！');
                document.getElementById('saveModal').style.display = 'none';
            } else {
                this.showError('保存失败：' + result.message);
            }
        } catch (error) {
            this.showError('保存失败：' + error.message);
        }
    }

    async showLoadModal() {
        try {
            const response = await fetch('/api/pages');
            const result = await response.json();
            
            const select = document.getElementById('loadFileSelect');
            select.innerHTML = '<option value="">请选择文件</option>';
            
            if (result.success && result.data.length > 0) {
                result.data.forEach(page => {
                    const option = document.createElement('option');
                    option.value = page.filename;
                    option.textContent = page.name;
                    select.appendChild(option);
                });
            }
            
            document.getElementById('loadModal').style.display = 'block';
        } catch (error) {
            this.showError('获取文件列表失败：' + error.message);
        }
    }

    async loadPage() {
        const filename = document.getElementById('loadFileSelect').value;
        if (!filename) {
            this.showError('请选择要读取的文件');
            return;
        }

        try {
            const response = await fetch(`/api/load/${filename}`);
            const result = await response.json();
            
            if (result.success) {
                this.loadPageData(result.data);
                this.showSuccess('读取成功！');
                document.getElementById('loadModal').style.display = 'none';
            } else {
                this.showError('读取失败：' + result.message);
            }
        } catch (error) {
            this.showError('读取失败：' + error.message);
        }
    }

    loadPageData(pageData) {
        // 清空当前画布
        this.elements = [];
        this.canvas.innerHTML = '<div class="canvas-placeholder"><p>拖拽左侧元素到此处开始设计</p></div>';
        this.selectElement(null);
        
        // 设置背景（只应用到画布）
        this.background = pageData.background || { color: '#ffffff', image: '' };
        this.canvas.style.backgroundColor = this.background.color;
        if (this.background.image) {
            this.canvas.style.backgroundImage = `url(${this.background.image})`;
            this.canvas.style.backgroundSize = 'cover';
            this.canvas.style.backgroundPosition = 'center';
            this.canvas.style.backgroundRepeat = 'no-repeat';
        } else {
            this.canvas.style.backgroundImage = 'none';
            this.canvas.style.backgroundSize = 'initial';
            this.canvas.style.backgroundPosition = 'initial';
            this.canvas.style.backgroundRepeat = 'initial';
        }
        
        // 加载元素
        this.elements = pageData.elements || [];
        this.elements.forEach(element => {
            this.renderElement(element);
        });
    }

    async generatePreview() {
        if (this.elements.length === 0) {
            this.showWarning('请先添加一些元素');
            return;
        }

        // 创建输入对话框
        const inputToast = this.showToast('请输入预览文件名', 'info', 0);
        inputToast.innerHTML = `
            <span class="toast-icon">ℹ️</span>
            <span class="toast-content">请输入预览文件名</span>
            <div style="display: flex; gap: 8px; margin-left: 10px; align-items: center;">
                <input type="text" id="previewFilename" value="preview_${Date.now()}" 
                       style="padding: 4px 8px; border: 1px solid #ddd; border-radius: 4px; font-size: 12px; width: 150px;">
                <button onclick="window.pageBuilder._confirmPreview()" 
                        style="background: #4CAF50; color: white; border: none; padding: 4px 12px; border-radius: 4px; cursor: pointer; font-size: 12px;">
                    生成
                </button>
                <button onclick="this.closest('.toast').remove()" 
                        style="background: #f44336; color: white; border: none; padding: 4px 12px; border-radius: 4px; cursor: pointer; font-size: 12px;">
                    取消
                </button>
            </div>
        `;
    }

    async _confirmPreview() {
        const filename = document.getElementById('previewFilename').value.trim();
        if (!filename) {
            this.showError('请输入文件名');
            return;
        }

        const pageData = {
            background: this.background,
            elements: this.elements
        };

        try {
            const response = await fetch('/api/preview', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ pageData, filename })
            });

            const result = await response.json();
            if (result.success) {
                this.showSuccess('预览生成成功！');
                window.open(result.url, '_blank');
                // 关闭输入对话框
                const inputToast = document.querySelector('#previewFilename').closest('.toast');
                if (inputToast) inputToast.remove();
            } else {
                this.showError('预览生成失败：' + result.message);
            }
        } catch (error) {
            this.showError('预览生成失败：' + error.message);
        }
    }

    // 结构库设置
    setupStructureLibrary() {
        const gridStructure = document.getElementById('gridStructure');
        const gridTooltip = document.getElementById('gridTooltip');
        const gridOptions = document.querySelectorAll('.grid-option');
        const cancelBtn = document.getElementById('cancelGrid');
        const confirmBtn = document.getElementById('confirmGrid');
        
        let selectedCols = 2; // 默认选择2列
        let isTooltipVisible = false;
        
        // 网格结构项点击显示气泡
        gridStructure.addEventListener('click', (e) => {
            e.stopPropagation();
            if (!isTooltipVisible) {
                this.positionTooltip(e.target, gridTooltip);
                gridTooltip.classList.add('show');
                gridStructure.classList.add('active');
                isTooltipVisible = true;
            } else {
                gridTooltip.classList.remove('show');
                gridStructure.classList.remove('active');
                isTooltipVisible = false;
            }
        });
        
        // 点击页面其他地方隐藏气泡
        document.addEventListener('click', (e) => {
            if (!gridStructure.contains(e.target) && !gridTooltip.contains(e.target)) {
                gridTooltip.classList.remove('show');
                gridStructure.classList.remove('active');
                isTooltipVisible = false;
            }
        });
        
        // 网格选项选择
        gridOptions.forEach(option => {
            option.addEventListener('click', (e) => {
                e.stopPropagation();
                // 移除其他选中状态
                gridOptions.forEach(opt => opt.classList.remove('selected'));
                // 添加选中状态
                option.classList.add('selected');
                selectedCols = parseInt(option.getAttribute('data-cols'));
            });
        });
        
        // 取消按钮
        cancelBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            gridTooltip.classList.remove('show');
            gridStructure.classList.remove('active');
            isTooltipVisible = false;
        });
        
        // 确定按钮
        confirmBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            this.createFullWidthGrid(selectedCols);
            gridTooltip.classList.remove('show');
            gridStructure.classList.remove('active');
            isTooltipVisible = false;
        });
        
        // 默认选择2列
        gridOptions[0].classList.add('selected');
    }
    
    // 定位气泡提示
    positionTooltip(target, tooltip) {
        const rect = target.getBoundingClientRect();
        const tooltipRect = tooltip.getBoundingClientRect();
        
        // 计算位置
        const left = rect.right + 10;
        const top = rect.top;
        
        // 确保不超出屏幕右边界
        const maxLeft = window.innerWidth - tooltipRect.width - 10;
        const finalLeft = Math.min(left, maxLeft);
        
        tooltip.style.left = finalLeft + 'px';
        tooltip.style.top = top + 'px';
    }
    
    // 手风琴功能设置（仅限主分类）
    setupAccordion() {
        // 只处理主分类的手风琴，子分类不需要
        const mainAccordionHeaders = document.querySelectorAll('h3.accordion-header');
        
        mainAccordionHeaders.forEach(header => {
            header.addEventListener('click', () => {
                const targetId = header.getAttribute('data-target');
                const content = document.getElementById(targetId);
                
                if (content) {
                    const isCollapsed = content.classList.contains('collapsed');
                    
                    if (isCollapsed) {
                        // 展开
                        content.classList.remove('collapsed');
                        header.classList.remove('collapsed');
                    } else {
                        // 收起
                        content.classList.add('collapsed');
                        header.classList.add('collapsed');
                    }
                }
            });
        });
    }
    
    // 创建全宽网格
    createFullWidthGrid(cols) {
        const elementId = `element_${++this.elementIdCounter}`;
        const element = {
            id: elementId,
            type: 'grid',
            content: '',
            style: {
                width: '375px', // 画布全宽
                height: '120px',
                display: 'grid',
                gap: '10px',
                padding: '15px',
                border: '2px dashed #007bff',
                backgroundColor: '#f8f9fa',
                borderRadius: '8px',
                position: 'relative',
                gridTemplateColumns: `repeat(${cols}, 1fr)`
            },
            x: 0, // 从画布左边开始
            y: 0, // 从画布顶部开始
            cols: cols
        };
        
        this.elements.push(element);
        this.renderElement(element);
        this.selectElement(element);
        
        this.showSuccess(`已创建${cols}列全宽网格`);
    }
}

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
    window.pageBuilder = new PageBuilder();
});
